<template>
	<view class="wrap">
		<view class="poster-box">
			<image v-if="img" :src="img" mode="widthFix" class="poster-img" @longpress="savePoster" />
				<view v-else class="empty">海报生成中…</view>
		</view>

		<!-- 操作区：主按钮 + 文字分享 -->
		<view class="actions">
		  <!-- 主按钮：保存（带emoji） -->
		  <button class="primary-btn" @click="savePoster">
		    📥 保存到相册
		  </button>
		
		  <!-- 文字+图标：分享给朋友 -->
		  <!-- 小程序用原生分享，但外观做成文字链接 -->
		  <!-- #ifdef MP-WEIXIN -->
		  <button class="link-share" open-type="share">
		    <image class="share-icon" src="../../static/icon/share.png" mode="aspectFit" />
		    <text>分享给朋友</text>
		  </button>
		  <!-- #endif -->
		
		  <!-- H5 / App 走降级方法，但外观一致 -->
		  <!-- #ifndef MP-WEIXIN -->
		  <view class="link-share" @click="shareFallback">
		    <image class="share-icon" src="../../static/icon/share.png" mode="aspectFit" />
		    <text>分享给朋友</text>
		  </view>
		  <!-- #endif -->
		</view>

	</view>
</template>

<script>
	export default {
		// 允许小程序右上角分享和按钮分享
		// #ifdef MP-WEIXIN
		options: {
			styleIsolation: 'shared'
		},
		// #endif
		data() {
			return {
				img: '',
				meta: { // 可选：用于拼分享文案
					classTopic: '',
					studentName: '',
					studentEnglishName: '',
					teacherName: '',
					classTimeBegin: '',
					classId: '',
					studentId: ''
				}
			}
		},
		onLoad(query) {
			try {
				if (query && query.payload) {
					const payload = JSON.parse(decodeURIComponent(query.payload))
					this.img = payload.img
					this.meta = {
						...this.meta,
						...payload
					}
				} else if (query && query.img) {
					this.img = decodeURIComponent(query.img)
				}
			} catch (e) {
				console.error(e)
			}
		},

		// #ifdef MP-WEIXIN
		onShareAppMessage() {
			// 自定义转发内容（朋友）
			const title =
				`📘${this.meta.classTopic}｜${this.meta.studentEnglishName || ''}${this.meta.studentName ? `（${this.meta.studentName}）` : ''}`
			const path =
				`/pages/sharePoster/index?payload=${encodeURIComponent(JSON.stringify({ img: this.img, ...this.meta }))}`
			return {
				title,
				path,
				imageUrl: this.img // 海报图作为分享卡片
			}
		},
		onShareTimeline() {
			// 朋友圈（如果需要）
			return {
				title: `📘${this.meta.classTopic}`,
				query: `payload=${encodeURIComponent(JSON.stringify({ img: this.img, ...this.meta }))}`,
				imageUrl: this.img
			}
		},
		// #endif

		methods: {
			savePoster() {
				if (!this.img) return
				uni.showLoading({
					title: '保存中'
				})
				uni.downloadFile({
					url: this.img,
					success: (res) => {
						if (res.statusCode === 200) {
							// 微信/APP 端保存到相册
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success: () => {
									uni.showToast({
										title: '已保存到相册',
										icon: 'success'
									})
								},
								fail: (err) => {
									console.error(err)
									uni.showToast({
										title: '保存失败',
										icon: 'none'
									})
								},
								complete: () => uni.hideLoading()
							})
						} else {
							uni.hideLoading()
							uni.showToast({
								title: '下载失败',
								icon: 'none'
							})
						}
					},
					fail: () => {
						uni.hideLoading()
						uni.showToast({
							title: '下载失败',
							icon: 'none'
						})
					}
				})
			},

			// 非微信端的分享降级处理
			shareFallback() {
				const shareText =
					`📘${this.meta.classTopic}｜${this.meta.studentEnglishName || ''}${this.meta.studentName ? `（${this.meta.studentName}）` : ''}`
				const shareUrl = this.img

				// H5：优先使用原生 Web Share API
				// #ifdef H5
				if (navigator && navigator.share) {
					navigator.share({
						title: shareText,
						text: shareText,
						url: shareUrl
					}).catch(() => {
						this.copy(shareUrl)
					})
				} else {
					this.copy(shareUrl)
				}
				// #endif

				// App：示例调用 uni.share（按需配置 provider）
				// #ifdef APP
				uni.share({
					provider: 'weixin', // 也可 'qq' 等
					type: 0,
					href: shareUrl,
					title: shareText,
					summary: shareText,
					imageUrl: this.img,
					success: () => uni.showToast({
						title: '已调起分享',
						icon: 'success'
					}),
					fail: () => this.copy(shareUrl)
				})
				// #endif
			},

			copy(text) {
				uni.setClipboardData({
					data: text,
					success: () => uni.showToast({
						title: '链接已复制',
						icon: 'none'
					})
				})
			}
		}
	}
</script>

<style scoped>
	.wrap {
		min-height: 100vh;
		padding: 24rpx 24rpx 80rpx;
		box-sizing: border-box;
		background: linear-gradient(to bottom, #e6f4ea 0%, #fdfaf4 100%);
	}

	.poster-box {
		background: #fff;
		border-radius: 20rpx;
		box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, .08);
		padding: 20rpx;
	}

	.poster-img {
		width: 100%;
		border-radius: 12rpx;
		display: block;
		animation: fadeIn .24s ease;
	}

	.empty {
		height: 300rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #999;
	}

	
	.actions {
	  margin-top: 20rpx;
	  display: flex;
	  align-items: center;
	  justify-content: space-between;
	  gap: 20rpx;
	}
	
	/* 主按钮：柔和渐变 + 微弹动效 */
	.primary-btn {
	  flex: 1;
	  height: 96rpx;
	  line-height: 96rpx;
	  border-radius: 20rpx;
	  font-size: 30rpx;
	  color: #fff;
	  background: linear-gradient(90deg, #3a6b3f, #5a8f5f);
	  box-shadow: 0 8rpx 22rpx rgba(58, 107, 63, 0.25);
	  transform: translateZ(0); /* 防抖 */
	  transition: transform .12s ease, box-shadow .12s ease, opacity .12s ease;
	}
	.primary-btn:active {
	  transform: scale(0.98);
	  box-shadow: 0 4rpx 12rpx rgba(58, 107, 63, 0.2);
	  opacity: .95;
	}
	
	/* 文字分享：做成“链接感”，但保持可点区域与触感 */
	.link-share {
	  height: 96rpx;
	  padding: 0 24rpx;
	  border-radius: 16rpx;
	  background: rgba(90, 143, 95, 0.08);
	  display: inline-flex;
	  align-items: center;
	  gap: 10rpx;
	  color: #3a6b3f;
	  font-size: 28rpx;
	  border: 2rpx solid rgba(90, 143, 95, 0.15);
	  transition: transform .12s ease, background .12s ease, border-color .12s ease, opacity .12s ease;
	}
	.link-share:active {
	  transform: translateY(2rpx);
	  background: rgba(90, 143, 95, 0.12);
	  border-color: rgba(90, 143, 95, 0.25);
	  opacity: .95;
	}
	
	/* 图标与文字对齐 */
	.share-icon {
	  width: 40rpx;
	  height: 40rpx;
	  opacity: 0.9;
	}
	
	/* H5 的悬浮态小增强（可选） */
	/* #ifdef H5 */
	.link-share:hover {
	  transform: translateY(-1rpx);
	}
	/* #endif */

</style>